<template>
  <div class="form">
    <el-form
      ref="form"
      :model="form"
      :rules="form_rules"
      :label-width="dialog.formLabelWidth"
      style="margin: 10px; width: auto"
    >
      <el-form-item prop="name" label="产品名:">
        <el-input type="text" v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item prop="type" label="车型:">
        <el-input type="text" v-model="form.type"></el-input>
      </el-form-item>
      <!-- <el-form-item prop="type" label="车型:">
        <el-select v-model="form.type" placeholder="请选择车型">
          <el-option
            v-for="item in tabList[0].child"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item prop="brand" label="品牌:">
        <el-input type="text" v-model="form.brand"></el-input>
      </el-form-item>
      <!-- <el-form-item prop="brand" label="品牌:">
        <el-select v-model="form.brand" placeholder="请选择品牌">
          <el-option
            v-for="item in tabList[1].child"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item prop="price" label="价格:">
        <el-input
          type="text"
          v-model="form.price"
          @blur="form.price = Number(form.price)"
        ></el-input>
      </el-form-item>
      <el-form-item prop="mileage" label="公里数:">
        <el-input
          type="text"
          v-model="form.mileage"
          @blur="form.mileage = Number(form.mileage)"
        ></el-input>
      </el-form-item>
      <el-form-item prop="age" label="车龄:">
        <el-input
          type="text"
          v-model="form.age"
          @blur="form.age = Number(form.age)"
        ></el-input>
      </el-form-item>
      <el-form-item prop="birthday" label="上牌日期:">
        <el-date-picker
          v-model="form.birthday"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="quality" label="是否精品:">
        <el-radio-group v-model="form.quality">
          <el-radio :label="1">精品</el-radio>
          <el-radio :label="0">不是精品</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="recommend" label="是否推荐:">
        <el-radio-group v-model="form.recommend">
          <el-radio :label="1">推荐</el-radio>
          <el-radio :label="0">不推荐</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="pic" label="产品图片">
        <el-upload
          list-type="picture-card"
          :headers="token"
          action="#"
          accept="image/*"
          :http-request="httpRequest"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :before-upload="beforeUploadFile"
          :file-list="fileList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item prop="description" label="车辆描述">
        <el-input
          type="textarea"
          :rows="4"
          v-model="form.description"
        ></el-input>
      </el-form-item>
      <el-form-item class="text_right">
        <el-button @click="handleBack">返 回</el-button>
        <el-button
          :disabled="this.type == 'view'"
          type="primary"
          @click="onSubmit('form')"
          >提 交</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getCategoryList } from "@/api/user";
import { mapState, mapGetters } from "vuex";
import axios from "axios";
import { addCar, getCarById, productupdate } from "@/api/car";
import AreaJson from "@/assets/datas/area.json";
import { getToken } from "@/utils/auth";
export default {
  name: "addFundDialogs",
  data() {
    let validateData = (rule, value, callback) => {
      if (value === "") {
        let text;
        if (rule.field == "income") {
          text = "收入";
        } else if (rule.field == "pay") {
          text = "支出";
        } else if (rule.field == "accoutCash") {
          text = "账户现金";
        }
        callback(new Error(text + "不能为空~"));
      } else {
        let numReg = /^[0-9]+.?[0-9]*$/;
        if (!numReg.test(value)) {
          callback(new Error("请输入正数值"));
        } else {
          callback();
        }
      }
    };
    return {
      tabList: [],
      dialogImageUrl: "",
      type: "",
      fileList: [],
      dialogVisible: false,
      disabled: false,
      areaData: [],
      baseUrl: "localhost:8000/updateimg",
      token: {
        Authorization: getToken("Token"),
      },
      paginations: {
        total: 0, // 总数
        pageIndex: 1, // 当前位于哪页
        pageSize: 20, // 1页显示多少条
        pageSizes: [5, 10, 15, 20], //每页显示多少条
        layout: "total, sizes, prev, pager, next, jumper", // 翻页属性
      },
      form: {
        name: "",
        type: "",
        brand: "",
        pricestr: "",
        mileage: "",
        age: "",
        status: 1,
        birthday: "",
        pic: "",
        price: "",
        minipic: "",
      },
      payType: [
        { label: "提现", value: "0" },
        { label: "提现手续费", value: "1" },
        { label: "提现锁定", value: "2" },
        { label: "理财服务退出", value: "3" },
        { label: "购买宜定盈", value: "4" },
        { label: "充值", value: "5" },
        { label: "优惠券", value: "6" },
        { label: "充值礼券", value: "7" },
        { label: "转账", value: "8" },
      ],
      form_rules: {
        username: [
          { required: true, message: "用户名不能为空！", trigger: "blur" },
        ],
        income: [{ required: true, validator: validateData, trigger: "blur" }],
        pay: [{ required: true, validator: validateData, trigger: "blur" }],
        accoutCash: [
          { required: true, validator: validateData, trigger: "blur" },
        ],
        incomePayType: [
          { required: true, message: "请选择收支类型", trigger: "change" },
        ],
        address: [{ required: true, message: "请选择籍贯", trigger: "change" }],
      },
      //详情弹框信息
      dialog: {
        width: "400px",
        formLabelWidth: "120px",
      },
    };
  },
  props: {
    dialogRow: Object,
  },
  computed: {
    ...mapGetters(["addFundDialog"]),
  },
  created() {
    this.areaData = AreaJson;
  },
  mounted() {
    this.getCategoryList();
    this.type = this.$route.query.type;
    let id = this.$route.query.id;
    if (this.type === "edit") {
      getCarById({ id: id }).then((res) => {
        this.form = res.data.data.data;
        this.fileList = this.form.pic.split(";").map((item) => {
          return {
            name: item,
            url: item,
          };
        });
      });
    } else {
      getCarById({ id: id }).then((res) => {
        this.form = res.data.data.data;
        this.fileList = this.form.pic.split(";").map((item) => {
          return {
            name: item,
            url: item,
          };
        });
      });
    }
  },
  methods: {
    async getCategoryList() {
      let para = {
        opcode: "1",
        pagesize: this.paginations.pageSize,
        page: this.paginations.pageIndex,
      };
      let res = await getCategoryList(para);
      var category = {
        1001: "车型",
        1002: "品牌",
        1003: "价格",
        1004: "公里数",
        1005: "车龄",
      };
      let dataList = new Array();
      let child = new Array();
      let dataDict = {};
      let data = res.data.data;
      for (let k in data) {
        dataDict["id"] = Number(k);
        dataDict["name"] = category[k];
        for (let j in data[k]) {
          data[k][j] = JSON.parse(data[k][j]);
          data[k][j]["id"] = Number(j);
          child.push(data[k][j]);
        }
        dataDict["child"] = child;
        dataList.push(dataDict);
        dataDict = {};
        child = [];
      }
      this.tabList = dataList;
    },
    handleBack() {
      this.$router.go(-1);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    beforeUploadFile(file) {
      console.log("before upload");
      console.log(file);
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      let size = file.size / 1024 / 1024;
      //   if (extension !== "xlsx") {
      //     this.$notify.warning({
      //       title: "警告",
      //       message: `只能上传Excel2017（即后缀是.xlsx）的文件`,
      //     });
      //   }
      //   if (size > 10) {
      //     this.$notify.warning({
      //       title: "警告",
      //       message: `文件大小不得超过10M`,
      //     });
      //   }
      return true;
    },
    httpRequest(data) {
      let param = new FormData(); // 创建form对象
      param.append("filePath", data.file); // 通过append向form对象添加数据
      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: getToken("Token"),
        },
      };
      axios.post("/updateimg", param, config).then((res) => {
        if (res.data.success) {
          this.fileList.push({
            url: res.data.data[0],
            name: data.file.uid,
          });
        }
      });
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    getCascaderObj(val, opt) {
      return val.map(function (value, index, array) {
        for (var item of opt) {
          if (item.value == value) {
            opt = item.children;
            return item.label;
          }
        }
        return null;
      });
    },
    handleChange(value) {
      console.log([...value]); // ["120000", "120200", "120223"]
      this.form.address = [...value];
      let vals = this.getCascaderObj([...value], this.areaData); // arr
      this.form.tableAddress = vals.join(",").replace(/,/g, "");
    },
    closeDialog() {
      this.$emit("closeDialog");
    },
    //表单提交
    onSubmit(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          //表单数据验证完成之后，提交数据;
          this.form.pic = this.fileList
            .map((item) => {
              return item.url;
            })
            .join(";");
          let obj = {
            opcode: "1111",
            productdata: {
              ...this.form,
            },
          };
          // edit
          if (this.type === "edit") {
            productupdate(obj).then((res) => {
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.handleBack();
              // this.$refs["form"].resetFields();
              // this.isVisible = false;
              // this.$emit("getFundList");
            });
          } else {
            // add
            this.form.pic = this.fileList
              .map((item) => {
                return item.url;
              })
              .join(";");
            let obj = {
              opcode: "1111",
              productdata: {
                ...this.form,
              },
            };
            addCar(obj).then((res) => {
              this.$message({
                message: "新增成功",
                type: "success",
              });
              this.$refs["form"].resetFields();
              this.isVisible = false;
              this.$emit("getFundList");
            });
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.search_container {
  margin-bottom: 20px;
}
.form {
  width: 600px;
}
.btnRight {
  float: right;
  margin-right: 0px !important;
}
.searchArea {
  background: rgba(255, 255, 255, 1);
  border-radius: 2px;
  padding: 18px 18px 0;
}
</style>
